package com.example.interceptor;

import com.example.common.Result;
import com.example.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 认证拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的URI
        String uri = request.getRequestURI();
        
        // 静态资源放行
        if (uri.startsWith("/static/") || uri.startsWith("/vue-qr/") || uri.startsWith("/upload/")) {
            return true;
        }
        
        // 处理跨域预检请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        
        // 获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        // 如果用户已登录，放行
        if (user != null) {
            return true;
        }
        
        // 判断是否是API请求
        if (uri.startsWith("/api/")) {
            // API请求返回JSON格式的未授权错误
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(Result.unauthorized()));
            writer.flush();
            writer.close();
        } else {
            // 非API请求重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/user/login");
        }
        
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行调用，但是在视图被渲染之前
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行
    }
}